﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Quick.Communicator
{
    public partial class SerialPortConfigFrm : Form
    {
        int m_ConfigCount = 0;
        List<SerialConfig> m_Configs = null;

        public SerialPortConfigFrm(int configCount = 1, params SerialConfig[]  configs)
        {
            m_ConfigCount = configCount;
            if (configs != null)
            {
                m_Configs = new List<SerialConfig>(configs);
            }
            InitializeComponent();
            Init();
        }
        public List<SerialConfig> GetConfigs()
        {
            return m_Configs;
        }
        private void Init()
        {
            for (int i = 0; i < m_ConfigCount; i++)
            {
                TabPage tp = new TabPage();
                tp.Name = $"tp_{i}";
                tp.Text = $"Config {i + 1}";
                tp.TabIndex = i;

                SerialPortConfigControl spcc = null;
                if (null != m_Configs && m_Configs.Count > i)
                {
                    spcc = new SerialPortConfigControl(m_Configs[i]);
                }
                else
                {
                    spcc = new SerialPortConfigControl();
                }
                spcc.Dock = System.Windows.Forms.DockStyle.Fill;
                spcc.Location = new System.Drawing.Point(3, 3);
                spcc.MinimumSize = new System.Drawing.Size(240, 220);
                spcc.Name = "serialPortConfigControl1";
                spcc.Size = new System.Drawing.Size(245, 231);
                spcc.TabIndex = 0;

                tp.Controls.Add(spcc);
                this.tabControl1.Controls.Add(tp);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            m_Configs = new List<SerialConfig>();
            for (int i = 0; i < tabControl1.TabPages.Count; i++)
            {
                var tp = tabControl1.TabPages[i];

                for (int j = 0; j < tp.Controls.Count; j++)
                {
                    if (tp.Controls[j] is SerialPortConfigControl)
                    {
                        var spcc = tp.Controls[j] as SerialPortConfigControl;
                        var config = spcc.GetConfig();
                        if (null == config)
                        {
                            return;
                        }
                        m_Configs.Add(config);
                    }
                }
            }
            this.DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
